import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
// 自动合并
let routes = []
const requireRouters = require.context('./modules', true, /\.js$/)
requireRouters.keys().forEach(fileName => {
  const routerConfig = requireRouters(fileName)
  const route = routerConfig.default || routerConfig
  routes.push(...route)
});
const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: routes
})
router.beforeEach((to, from, next) => {
    let isLogin = !!localStorage.getItem('dangjianToken')
    if (to.name === 'login') {
        next()
    } else if (!isLogin && to.name !== 'login' && to.meta.requireAuth) {
        !isLogin ? next({ name: 'login' }) : next()
    } else {
        next()
    }
    const resetMetaArr = ['noticeDetail', 'bulletinDetail', 'messageDetail', 'mtdetail']
    if (resetMetaArr.includes(to.name)) {
        to.meta.activeName = from.name
    }
})
const originalPush = Router.prototype.push
Router.prototype.push = function(location) {
    return originalPush.call(this, location).catch(err => err)
}
export default router